package com.son.hotel.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.son.hotel.common.ErrorCode;
import com.son.hotel.common.Result;
import com.son.hotel.domain.Admin;
import com.son.hotel.execption.BusinessException;
import com.son.hotel.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    @Operation(summary = "登录-admin")
    @PostMapping("/login")
    public Result<Admin> adminLogin(@RequestBody Admin admin, HttpServletRequest httpServletRequest){
        String password = admin.getPassword();
        String phone = admin.getPhone();
        log.info("admin:{}",admin);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("password",password).eq("phone",phone);
        Admin adminInfo = adminService.getOne(queryWrapper);
        if (BeanUtil.isEmpty(adminInfo)){
            throw new BusinessException(ErrorCode.PARAMETER_ERROR,"管理员不存在");
        }
        log.info("adminInfo:{}",adminInfo);
        //admin存进session
        httpServletRequest.getSession().setAttribute("password",password);
        httpServletRequest.getSession().setAttribute("phone",phone);
        return Result.success("200",adminInfo);
    }

    @Operation(summary = "获取当前admin信息")
    @GetMapping("/current")
    public Result<Admin> getCurrentAdmin(HttpServletRequest httpServletRequest){
        String password = (String)httpServletRequest.getSession().getAttribute("password");
        String phone = (String)httpServletRequest.getSession().getAttribute("phone");

        Admin admin = new Admin();
        admin.setName("admin");
        admin.setPhone(phone);
        admin.setPassword(password);

        return Result.success("200",admin);
    }


    /**
     * admin和customer共用同一个logout，但是customer只是做了路由跳转
     * @param httpServletRequest
     * @return
     */
    @Operation(summary = "退出-admin")
    @GetMapping("/logout")
    public Result<ErrorCode> logout(HttpServletRequest httpServletRequest){
        httpServletRequest.getSession().removeAttribute("phone");
        httpServletRequest.getSession().removeAttribute("password");

        return Result.success("200",ErrorCode.SUCCESS);
    }


}
